<?php namespace App\Core\Service\Services;

use App\Core\Repository\Criterias\FixedCriteria;
use App\Core\Repository\Criterias\InCriteria;

trait Indexer{
    
    protected $indexKeyInInput;//请求中索引名
    protected $indexKeysInInput;//请求中多索引名
    
    //设置索引名称
    protected function setIndexName($indexName){
        $this->indexKeyInInput = $indexName;
    }

    //获取索引名
    protected function getIndexName($metaName = 'meta'){
        return $this->indexKeyInInput ? $this->indexKeyInInput : $this->getMeta($metaName)->getPrimaryKey();
    }
    
    //设置索引名称
    protected function setIndexesName($indexName){
        $this->indexKeysInInput = $indexName;
    }
    
    //获取批量索引名
    protected function getIndexesName($metaName = 'meta'){
        return $this->indexKeysInInput ? $this->indexKeysInInput : $this->getIndexName($metaName).'s';
    }
    
    //用户输入获取索引值
    protected function getIndexFromInput($indexKey = ''){
        return $this->formData->get($indexKey ? $indexKey : $this->getIndexName());
    }
    
    //获取批量操作的用户输入索引值
    protected function getIndexesFromInput($indexesKey = ''){
        $indexes = $this->formData->get($indexesKey ? $indexesKey : $this->getIndexesName());
        return is_array($indexes) ? $indexes : explode(',', $indexes);
    }
    
    //获取索引限制条件
    protected function getIndexCriteria($metaName = 'meta'){
        $key = $this->getIndexName($metaName);
        $value = $this->getIndexFromInput($key);
        $criteria = new FixedCriteria($key, $value);
        return $criteria->setName('index');
    }
    
    //获取多索引限制条件
    protected function getIndexesCriteria($metaName = 'meta'){
        $key = $this->getIndexName($metaName);
        $inputKey = $this->getIndexesName($metaName);
        $value = $this->getIndexesFromInput($inputKey);        
        $criteria = new InCriteria($key, $value);
        return $criteria->setName('indexes');
    }
}